<template>
  <div class="transfer-form-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">新增调拨单</h1>
    </div>

    <!-- 基础信息区域 -->
    <div class="form-section">
      <div class="section-header">
        <h2 class="section-title">基础信息</h2>
      </div>

      <el-form ref="basicFormRef" :model="basicForm" :rules="basicRules" label-width="120px" class="basic-form">
        <div class="form-row">
          <!-- 左列 -->
          <div class="form-column">
            <el-form-item label="调拨单号" prop="movingCode" required>
              <el-input v-model="basicForm.movingCode" placeholder="自动获取系统编号" disabled class="form-input" />
            </el-form-item>

            <el-form-item label="调拨申请日期" prop="createTime" required>
              <el-date-picker v-model="basicForm.createTime" type="datetime" placeholder="请选择"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss.SSS[Z]" class="form-input" />
            </el-form-item>

            <el-form-item label="调入仓库" prop="original_Position" required>
              <div class="input-with-button">
                <el-select v-model="basicForm.original_Position" placeholder="请选择" class="form-input warehouse-select"
                  clearable>

                  <el-option v-for="item in Warehousement" :label="item.warehouse_Name" :value="item.id" />
                </el-select>
                <el-button type="success" size="small" class="set-btn">设置</el-button>
              </div>
            </el-form-item>

            <el-form-item label="备注" prop="notes">
              <el-input v-model="basicForm.notes" type="textarea" :rows="3" placeholder="请输入" class="form-input" />
            </el-form-item>
          </div>

          <!-- 右列 -->
          <div class="form-column">
            <el-form-item label="调拨类型" prop="allotWarehouseType">
              <el-select v-model="basicForm.allotWarehouseType" placeholder="请选择" class="form-input" clearable>
                <el-option label="货品调拨" value="货品调拨" />
                <el-option label="设备调拨" value="设备调拨" />
                <el-option label="其他调拨" value="其他调拨" />

              </el-select>
            </el-form-item>

            <el-form-item label="调出仓库" prop="original_Warehouse" required>
              <div class="input-with-button">
                <el-select v-model="basicForm.original_Warehouse" placeholder="请选择" class="form-input warehouse-select"
                  clearable @change="handleWarehouseChange">
                  <el-option v-for="item in Warehousement" :label="item.warehouse_Name" :value="item.id"
                    :key="item.id" />
                </el-select>
                <el-button type="success" size="small" class="set-btn">设置</el-button>
              </div>
            </el-form-item>

            <el-form-item label="经办人" prop="handler">
              <div class="input-with-button">
                <el-select v-model="basicForm.reviewer" placeholder="请选择" class="form-input" clearable>
                  <el-option label="吴维昊" value="吴维昊" />
                  <el-option label="王雨龙" value="王雨龙" />
                  <el-option label="张可欣" value="张可欣" />
                  <el-option label="赵姝雅" value="赵姝雅" />
                  <el-option label="段栋兴" value="段栋兴" />
                </el-select>
                <el-button size="small" class="more-btn">...</el-button>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 调拨明细区域 -->
    <div class="form-section">
      <div class="section-header">
        <h2 class="section-title">调拨明细</h2>
        <div class="section-actions">
          <el-button type="success" @click="addTransferItem" class="action-btn">
            <el-icon>
              <Plus />
            </el-icon>
            添加
          </el-button>
          <el-button @click="removeSelectedItems" class="action-btn remove-btn">
            <el-icon>
              <Delete />
            </el-icon>
            移除
          </el-button>
          <el-button @click="debugInfo" type="info" size="small" class="action-btn">
            调试信息
          </el-button>
          <span class="debug-info">可用货品: {{ availableProducts.length }} 个</span>
        </div>
      </div>

      <div class="table-container">
        <el-table ref="transferTableRef" :data="transferItems" @selection-change="handleSelectionChange"
          class="transfer-table">
          <el-table-column type="selection" width="55" :selectable="() => true">
            <template #header>
              <el-checkbox v-model="isAllSelected" :indeterminate="isIndeterminate" />
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="productName" label="货品名称" width="150" />
          <el-table-column prop="productCode" label="货品编号" width="150" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="120" />
          <el-table-column prop="productType" label="货品类型" width="120" />
          <el-table-column prop="outboundStock" label="调出仓库当前库存" width="150" />
          <el-table-column prop="inboundStock" label="调入仓库当前库存" width="150" />
          <el-table-column prop="transferQuantity" label="调拨数量" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.transferQuantity" placeholder="请输入" @input="calculateAmount(scope.row)"
                @focus="handleProductFocus(scope.row)" class="quantity-input" />
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="入库单价" width="120" />
          <el-table-column prop="transferAmount" label="调拨金额" width="120">
            <template #default="scope">
              <span class="amount-display">{{ scope.row.transferAmount || '0.00' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="text" @click="removeItem(scope.$index)" class="remove-link">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 合计信息 -->
        <div class="summary-section">
          <div class="summary-item">
            <span class="summary-label">调拨种类:</span>
            <span class="summary-value">{{ transferItems.length }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">调拨数量:</span>
            <span class="summary-value">{{ totalQuantity }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">调拨金额:</span>
            <span class="summary-value">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="goBack" class="cancel-btn">取消</el-button>
      <el-button type="primary" @click="submitForm" class="submit-btn">提交</el-button>
    </div>

    <!-- 货品选择弹窗 -->
    <el-dialog v-model="productDialogVisible" title="选择货品" width="800px" class="product-dialog">
      <div class="dialog-content">
        <el-table :data="availableProducts" @selection-change="handleProductSelection" class="product-table"
          ref="productTableRef">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="product_Name" label="货品名称" />
          <el-table-column prop="product_Number" label="货品编号" />
          <el-table-column prop="specifications" label="规格型号" />
          <el-table-column prop="unit_Name" label="单位" />
          <el-table-column prop="price" label="入库单价" />
          <el-table-column prop="warehouse_InOrOutCount" label="当前库存" />
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElCheckbox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { statementRed } from '@/http/axiosHelper'
import axios from 'axios'
const router = useRouter()

// 表格引用
const transferTableRef = ref()

// 类型安全的数字转换函数
const safeNumber = (value: any, defaultValue: number = 0): number => {
  if (value === null || value === undefined || value === '') {
    return defaultValue
  }
  const num = Number(value)
  return isNaN(num) ? defaultValue : num
}

// 定义类型接口
interface TransferItem {
  productName: string
  productCode: string
  specification: string
  unit: string
  productType: string
  outboundStock: string
  inboundStock: string
  transferQuantity: string
  unitPrice: string
  transferAmount: string
  id?: number // 添加产品ID字段
}

interface Product {
  productName: string
  productCode: string
  specification: string
  unit: string
  productType: string
  stock: string
}

// 定义基础表单类型
interface BasicForm {
  tableType: number
  movingCode: string
  allotWarehouseType: string
  createTime: string
  original_Warehouse: string | number
  original_Position: string | number
  reviewer: string
  notes: string
  allotCount: number
  state: string
  batch: string
  product_Id: number
  createUse: number
}

// 定义提交数据的类型
interface SubmitInventoryData {
  tableType: number
  movingCode: string
  allotWarehouseType: string
  createTime: string
  original_Warehouse: number
  original_Position: number
  reviewer: string
  notes: string
  allotCount: number
  state: string
  batch: string
  product_Id: number
  createUse: number
}

interface SubmitData {
  createInventories: SubmitInventoryData[]
}

// 定义提交数据的类型
interface SubmitInventoryData {
  tableType: number
  movingCode: string
  allotWarehouseType: string
  createTime: string
  original_Warehouse: number
  original_Position: number
  reviewer: string
  notes: string
  allotCount: number
  state: string
  batch: string
  product_Id: number
  createUse: number
}

interface SubmitData {
  createInventories: SubmitInventoryData[]
}

// 基础表单数据
const basicForm = reactive<BasicForm>({
  tableType: 2,
  movingCode: "",
  allotWarehouseType: "", // 不设置默认值，让用户必须选择
  createTime: "",
  original_Warehouse: "", // 调出仓库
  original_Position: "", // 调入仓库
  reviewer: "",
  notes: "",
  allotCount: 0,
  state: "待审批",
  batch: "",
  product_Id: 0,
  createUse: 1039
})
const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0

})

const page2 = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0

})
onMounted(() => {
  Warehousementdata();
})




const Warehousement = ref()
const Warehousementdata = () => {
  console.log('获取仓库数据...')
  statementRed.get("api/Inventory/GetWarehouse")
    .then(res => {
      console.log('仓库API响应:', res)
      console.log('仓库数据:', res.data.data)
      Warehousement.value = res.data.data
    })
    .catch(error => {
      console.error('获取仓库数据失败:', error)
    })
}


// 基础表单验证规则
const basicRules = {
  createTime: [
    { required: true, message: '请选择调拨申请日期', trigger: 'change' }
  ],
  original_Position: [
    { required: true, message: '请选择调入仓库', trigger: 'change' }
  ],
  original_Warehouse: [
    { required: true, message: '请选择调出仓库', trigger: 'change' }
  ],
  allotWarehouseType: [
    { required: true, message: '请选择调拨类型', trigger: 'change' }
  ],
  reviewer: [
    { required: true, message: '请选择经办人', trigger: 'change' }
  ]
}

// 调拨明细数据
const transferItems = ref<TransferItem[]>([])

// 选中的行
const selectedRows = ref<TransferItem[]>([])
const selectedProducts = ref<any[]>([])

// 弹窗控制
const productDialogVisible = ref(false)

// 可用货品数据
const availableProducts = ref([])
const ProductInventoryTransfer = (Warehouse_ID: any) => {
  console.log('调用 ProductInventoryTransfer，仓库ID:', Warehouse_ID)

  if (!Warehouse_ID) {
    console.warn('仓库ID为空，无法获取货品')
    availableProducts.value = []
    return
  }

  statementRed.get("api/TwoWorkOrder/GetInventoryHandle", { params: { Warehouse_ID: Warehouse_ID } })
    .then(res => {
      console.log('API响应:', res)
      console.log('响应数据:', res.data)
      console.log('产品数据:', res.data.data)

      if (res.data && res.data.data && Array.isArray(res.data.data)) {
        availableProducts.value = res.data.data
        console.log('更新后的可用产品:', availableProducts.value)
      } else {
        console.warn('API返回的数据结构不正确:', res.data)
        availableProducts.value = []
      }
    })
    .catch(error => {
      console.error('API调用失败:', error)
      availableProducts.value = []
    })
}

// 处理仓库选择变化
const handleWarehouseChange = (selectedWarehouseId: any) => {
  console.log('选择的仓库ID:', selectedWarehouseId)
  if (selectedWarehouseId) {
    ProductInventoryTransfer(selectedWarehouseId)
  } else {
    // 如果清除了选择，清空可用货品列表
    availableProducts.value = []
  }
}

// 计算属性
const totalQuantity = computed(() => {
  return transferItems.value.reduce((sum, item) => {
    const quantity = parseFloat(item.transferQuantity) || 0
    return sum + quantity
  }, 0)
})

const totalAmount = computed(() => {
  return transferItems.value.reduce((sum, item) => {
    return sum + parseFloat(item.transferAmount || '0')
  }, 0)
})

// 判断是否全选
const isAllSelected = computed({
  get: () => {
    return transferItems.value.length > 0 && selectedRows.value.length === transferItems.value.length
  },
  set: (val: boolean) => {
    handleSelectAll(val)
  }
})

// 判断是否部分选中
const isIndeterminate = computed(() => {
  return selectedRows.value.length > 0 && selectedRows.value.length < transferItems.value.length
})

// 方法
const addTransferItem = () => {
  console.log('打开产品选择弹窗')
  console.log('当前可用产品数量:', availableProducts.value.length)
  console.log('当前可用产品:', availableProducts.value)
  console.log('当前选择的调出仓库ID:', basicForm.original_Warehouse)

  // 检查是否选择了调出仓库
  if (!basicForm.original_Warehouse) {
    ElMessage.warning('请先选择调出仓库')
    return
  }

  // 检查是否有可用货品
  if (availableProducts.value.length === 0) {
    ElMessage.warning('当前仓库暂无可用货品')
    return
  }

  productDialogVisible.value = true
}

// 全选/取消全选
const handleSelectAll = (val: boolean) => {
  if (val) {
    // 全选
    transferItems.value.forEach(row => {
      transferTableRef.value?.toggleRowSelection(row, true)
    })
  } else {
    // 取消全选
    transferTableRef.value?.clearSelection()
  }
}

const removeSelectedItems = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要移除的货品')
    return
  }

  const indices = selectedRows.value.map(row => transferItems.value.indexOf(row)).sort((a, b) => b - a)
  indices.forEach(index => {
    transferItems.value.splice(index, 1)
  })

  ElMessage.success('移除成功')
}

const removeItem = (index: number) => {
  transferItems.value.splice(index, 1)
  ElMessage.success('移除成功')
}

const handleSelectionChange = (selection: TransferItem[]) => {
  selectedRows.value = selection
  console.log('选中的行:', selection.length, '总行数:', transferItems.value.length)
}

const handleProductSelection = (selection: any[]) => {
  selectedProducts.value = selection
}

const confirmProductSelection = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择货品')
    return
  }

  selectedProducts.value.forEach((product: any) => {
    const newItem: TransferItem = {
      productName: product.product_Name || product.productName,
      productCode: product.product_Number || product.productCode,
      specification: product.specifications || product.specification,
      unit: product.unit_Name || product.unit,
      productType: product.productType || '货品',
      outboundStock: product.warehouse_InOrOutCount?.toString() || product.stock || '0',
      inboundStock: '0',
      transferQuantity: '',
      unitPrice: product.price?.toString() || '50.00',
      transferAmount: '0.00',
      id: product.id || product.product_Id // 添加产品ID
    }
    transferItems.value.push(newItem)
  })

  productDialogVisible.value = false
  ElMessage.success('添加货品成功')
}

const calculateAmount = (item: TransferItem) => {
  const quantity = parseFloat(item.transferQuantity) || 0
  const unitPrice = parseFloat(item.unitPrice) || 0
  item.transferAmount = (quantity * unitPrice).toFixed(2)

  // 更新basicForm中的总调拨数量
  updateTotalAllotCount()
}

// 更新总调拨数量
const updateTotalAllotCount = () => {
  const totalCount = transferItems.value.reduce((sum, item) => {
    return sum + (parseFloat(item.transferQuantity) || 0)
  }, 0)
  basicForm.allotCount = totalCount
}

// 处理商品焦点事件，更新当前选中的产品ID
const handleProductFocus = (item: TransferItem) => {
  if (item.id) {
    basicForm.product_Id = item.id
  }
}

const validateForm = (): boolean => {
  try {
    // 验证基础信息
    if (!basicForm.original_Position) {
      ElMessage.warning('请选择调入仓库!')
      return false
    }

    if (!basicForm.original_Warehouse) {
      ElMessage.warning('请选择调出仓库!')
      return false
    }

    if (basicForm.original_Warehouse === basicForm.original_Position) {
      ElMessage.warning('调入仓库和调出仓库不能为同一仓库!')
      return false
    }

    if (!basicForm.reviewer) {
      ElMessage.warning('请选择经办人!')
      return false
    }

    if (!basicForm.createTime) {
      ElMessage.warning('请选择调拨申请日期!')
      return false
    }

    // 验证调拨明细
    if (transferItems.value.length === 0) {
      ElMessage.warning('请选择货品!')
      return false
    }

    // 验证数量
    for (let i = 0; i < transferItems.value.length; i++) {
      const item = transferItems.value[i]
      const quantity = parseFloat(item.transferQuantity) || 0

      if (quantity <= 0) {
        ElMessage.error(`第${i + 1}行货品数量必须大于0!`)
        return false
      }

      // 验证库存是否足够
      const outboundStock = parseFloat(item.outboundStock) || 0
      if (quantity > outboundStock) {
        ElMessage.error(`第${i + 1}行货品库存不足,当前库存: ${outboundStock}, 调拨数量: ${quantity}`)
        return false
      }
    }

    return true
  } catch (error) {
    console.error('表单验证出错:', error)
    ElMessage.error('表单验证过程中发生错误')
    return false
  }
}

const submitForm = async () => {
  // 基础验证
  if (!validateForm()) {
    return
  }

  // 检查库存下限（异步确认）
  for (let item of transferItems.value) {
    const quantity = parseFloat(item.transferQuantity) || 0
    const outboundStock = parseFloat(item.outboundStock) || 0
    const lowerLimit = outboundStock * 0.1 // 假设下限为库存的10%

    if (outboundStock - quantity < lowerLimit) {
      try {
        await ElMessageBox.confirm(
          '当前操作库存将低于货品库存下限,是否执行调拨?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
      } catch {
        // 用户取消操作
        return
      }
    }
  }

  // 验证通过后执行提交逻辑
  try {
    // 准备提交数据，按照API要求的格式
    const submitData: SubmitData = {
      createInventories: [
        {
          tableType: safeNumber(basicForm.tableType, 2),
          movingCode: basicForm.movingCode || '',
          allotWarehouseType: basicForm.allotWarehouseType || '货品调拨',
          createTime: basicForm.createTime || new Date().toISOString(),
          original_Warehouse: safeNumber(basicForm.original_Warehouse, 0),
          original_Position: safeNumber(basicForm.original_Position, 0),
          reviewer: basicForm.reviewer || '',
          notes: basicForm.notes || '',
          allotCount: safeNumber(basicForm.allotCount, 0),
          state: basicForm.state || '待审批',
          batch: basicForm.batch || basicForm.movingCode,
          product_Id: safeNumber(basicForm.product_Id, 0),
          createUse: safeNumber(basicForm.createUse, 1039)
        }
      ]
    }

    console.log('提交的数据:', submitData) // 调试用
    console.log('调拨明细数量:', transferItems.value.length) // 调试用

    // 在控制台中以表格形式显示数据，便于调试
    console.table(submitData.createInventories[0])

    // 确保 product_Id 使用第一个产品的ID
    if (transferItems.value.length > 0 && transferItems.value[0].id !== undefined) {
      const productId = safeNumber(transferItems.value[0].id, 0)
      if (productId > 0) {
        submitData.createInventories[0].product_Id = productId
        console.log('设置产品ID:', submitData.createInventories[0].product_Id)
      }
    }

    // 验证关键字段
    if (!submitData.createInventories[0].movingCode) {
      ElMessage.error('调拨单号不能为空')
      return
    }

    if (!submitData.createInventories[0].original_Warehouse) {
      ElMessage.error('调出仓库不能为空')
      return
    }

    if (!submitData.createInventories[0].original_Position) {
      ElMessage.error('调入仓库不能为空')
      return
    }

    if (!submitData.createInventories[0].reviewer) {
      ElMessage.error('经办人不能为空')
      return
    }

    // 最终验证：确保所有必要字段都有值
    const requiredFields = ['movingCode', 'allotWarehouseType', 'createTime', 'original_Warehouse', 'original_Position', 'reviewer']
    for (const field of requiredFields) {
      const fieldValue = submitData.createInventories[0][field as keyof typeof submitData.createInventories[0]]
      if (!fieldValue) {
        ElMessage.error(`字段 ${field} 不能为空`)
        return
      }
    }

    // 验证数字字段
    const numericFields = ['original_Warehouse', 'original_Position', 'allotCount', 'product_Id']
    for (const field of numericFields) {
      const value = submitData.createInventories[0][field as keyof typeof submitData.createInventories[0]]
      if (typeof value !== 'number' || value <= 0) {
        ElMessage.error(`字段 ${field} 必须是大于0的数字`)
        return
      }
    }

    console.log('所有验证通过，开始提交...')
    console.log('最终提交数据:', JSON.stringify(submitData, null, 2))

    const res = await statementRed.post("api/Workorder/CreateInventoryHandle", submitData)
    console.log('API响应:', res) // 调试用

    if (res.data.code == 200) {
      ElMessage.success(res.data.msg)
      goBack() // 成功后返回上一页
    } else {
      ElMessage.error(res.data.msg || '提交失败') // 失败时显示错误信息
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

const goBack = () => {
  router.go(-1)
}

// 调试信息函数
const debugInfo = () => {
  console.log('=== 调试信息 ===')
  console.log('基础表单数据:', basicForm)
  console.log('调出仓库ID:', basicForm.original_Warehouse)
  console.log('调入仓库ID:', basicForm.original_Position)
  console.log('可用货品数量:', availableProducts.value.length)
  console.log('可用货品数据:', availableProducts.value)
  console.log('调拨明细数量:', transferItems.value.length)
  console.log('调拨明细数据:', transferItems.value)

  // 显示弹窗信息
  ElMessageBox.alert(
    `调试信息：
    
基础表单数据: ${JSON.stringify(basicForm, null, 2)}

调出仓库ID: ${basicForm.original_Warehouse}
调入仓库ID: ${basicForm.original_Position}
可用货品数量: ${availableProducts.value.length}
调拨明细数量: ${transferItems.value.length}

详细日志请查看浏览器控制台`,
    '调试信息',
    {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true
    }
  )
}



// 生成调拨单号
const generateTransferNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  basicForm.movingCode = `DB${year}${month}${day}${random}`
  basicForm.batch = `DB${year}${month}${day}${random}`
}

onMounted(() => {
  console.log('页面初始化开始...')
  generateTransferNumber()
  basicForm.createTime = new Date().toISOString() // 使用完整的ISO格式
  updateTotalAllotCount() // 初始化总调拨数量

  // 不再自动设置调拨类型，让用户必须选择
  console.log('初始化后的表单数据:', basicForm)
})
</script>

<style scoped>
.transfer-form-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
  text-align: center;
}

.form-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.section-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.debug-info {
  margin-left: 16px;
  padding: 4px 8px;
  background: #e3f2fd;
  border-radius: 4px;
  font-size: 12px;
  color: #1976d2;
  border: 1px solid #bbdefb;
}

.action-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.remove-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.remove-btn:hover {
  background: linear-gradient(135deg, #ee5a52, #d63031);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.basic-form {
  width: 100%;
}

.form-row {
  display: flex;
  gap: 40px;
}

.form-column {
  flex: 1;
}

.form-input {
  width: 100%;
}

.warehouse-select {
  min-width: 200px;
  width: 100%;
}

.warehouse-select :deep(.el-input__wrapper) {
  min-width: 200px;
}

.warehouse-select :deep(.el-input__inner) {
  min-width: 200px;
}

/* 美化清除按钮 */
.warehouse-select :deep(.el-select__caret) {
  color: #909399;
}

.warehouse-select :deep(.el-select__caret.is-reverse) {
  color: #409eff;
}

.warehouse-select :deep(.el-input__suffix) {
  right: 5px;
}

.input-with-button {
  display: flex;
  gap: 8px;
  align-items: center;
  width: 100%;
}

.input-with-button .form-input {
  flex: 1;
  min-width: 0;
  /* 允许flex项目收缩 */
}

.input-with-button .warehouse-select {
  flex: 1;
  min-width: 200px;
}

.set-btn {
  background: linear-gradient(135deg, #28a745, #20c997);
  border: none;
  color: white;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}

.set-btn:hover {
  background: linear-gradient(135deg, #218838, #1e7e34);
  transform: translateY(-1px);
}

.more-btn {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}

.more-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
  color: #495057;
}

.table-container {
  margin-top: 20px;
}

.transfer-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.transfer-table :deep(.el-table__header-wrapper) {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}

.transfer-table :deep(.el-table__header) {
  color: #2c3e50;
  font-weight: 600;
}

.transfer-table :deep(.el-table__body) {
  color: #2c3e50;
}

.transfer-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.transfer-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.quantity-input {
  width: 100%;
}

.amount-display {
  font-weight: 600;
  color: #67c23a;
}

.remove-link {
  color: #28a745;
  font-weight: 500;
}

.remove-link:hover {
  color: #218838;
  text-decoration: underline;
}

.summary-section {
  display: flex;
  gap: 40px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-weight: 500;
  color: #6c757d;
}

.summary-value {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 32px;
}

.cancel-btn {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
  color: #495057;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  color: white;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.product-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.product-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 20px;
}

.product-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.product-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.product-table {
  border-radius: 8px;
  overflow: hidden;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .transfer-form-container {
    padding: 16px;
  }

  .form-row {
    flex-direction: column;
    gap: 20px;
  }

  .summary-section {
    flex-direction: column;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .section-actions {
    width: 100%;
    justify-content: center;
  }

  .action-btn {
    flex: 1;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}
</style>
